<template>
  <view>
    <uni-forms ref="formRef" label-width="0" :rules="formRules" :model="formData">
      <uni-forms-item name="mobile">
        <uni-easyinput v-model="formData.mobile" type="text" placeholder="请输入手机号" />
      </uni-forms-item>
      <uni-forms-item name="password">
        <uni-easyinput v-model="formData.password" type="password" placeholder="请输入密码" />
      </uni-forms-item>
      <uni-forms-item name="intro">
        <uni-easyinput v-model="formData.intro" type="textarea" placeholder="请输入自我介绍" />
      </uni-forms-item>
      <uni-forms-item>
        <button type="primary" @click="onSubmit">提交</button>
      </uni-forms-item>
    </uni-forms>
  </view>
</template>

<script lang="ts">
import { ref } from 'vue';
export default {
  options: {
    // 解除组件之间的样式隔离
    styleIsolation: 'shared'
  },
  setup() {
    // 0. 定义一个对象用于绑定表单
    const formRef = ref();

    // 1. 数据对象
    const formData = ref({
      mobile: '',
      password: '',
      intro: ''
    });

    // 2. 校验规则对象
    const formRules = {
      mobile: {
        rules: [
          // 非空校验
          { required: true, errorMessage: '手机号码不能为空' },
          // 格式校验
          { pattern: /^[1][3-8][0-9]{9}$/, errorMessage: '手机号码不正确' }
        ]
      },
      password: {
        rules: [
          // 非空校验
          { required: true, errorMessage: '密码不能为空' },
          // 格式校验
          { pattern: /^[a-zA-Z0-9]{8}$/, errorMessage: '密码格式不正确' }
        ]
      },
      intro: {
        rules: [
          // 非空校验
          { required: true, errorMessage: '自我介绍不能为空' }
        ]
      }
    };

    // 提交
    const onSubmit = async () => {
      try {
        const res = await formRef.value.validate();
        console.log(res);
      } catch (e) {
        console.log(e);
      }
    };

    return { formData, onSubmit, formRules, formRef };
  }
};
</script>

<style lang="scss">
.uni-forms {
  padding: 40rpx;
}
</style>
